//
//  Oauth2Controller.swift
//  微博项目
//
//  Created by admin on 16/3/4.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class Oauth2Controller: UIViewController,UIWebViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        let appKey = "2502786379"
        let redirectURL = "http://jinblog.com"
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectURL)&response_type=code"
        let url = NSURL(string: urlStr)
        let request = NSURLRequest(URL: url!)
        
        let web = UIWebView(frame:UIScreen.mainScreen().bounds)
        web.delegate = self
        self.view.addSubview(web)
        web.loadRequest(request)
        // Do any additional setup after loading the view.
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // http://jinblog.com/?code=dc46d9032f608b8297c7a77337a3a19a
        let url = "\(request.URL!)"
        let range:Range! = url.rangeOfString("http://jinblog.com/?code=")
        if range == nil
        {
            return true
        }
        else
        {
            Account.requestAccountWithCode(url.substringFromIndex(range.endIndex), success: { (account) -> (Void) in
                    if account != nil
                    {
                        MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
                        
                    }
                ChoiceController.chooseController()
                }, faild: { (task, error) -> Void in
                    print(error)
            })
            return false
        }
    }
    func webViewDidStartLoad(webView: UIWebView) {
        let hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
        // hud.label.text = "正在加载中..."
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
    }
    deinit
    {
        print("认证控制器销毁啦！！！")
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
